package com.code2roc.fastboot.system.setting.controller;

import com.code2roc.fastboot.model.ZTreeNode;
import com.code2roc.fastboot.system.setting.bizlogic.MenuLogic;
import com.code2roc.fastboot.system.setting.model.SystemMenuDO;
import com.code2roc.fastboot.system.setting.service.ISystemMenuService;
import com.code2roc.fastboot.model.BaseBootController;
import com.code2roc.fastboot.util.ZTreeBuilder;
import com.code2roc.fastboot.framework.extra.formupdate.UpdateRequestBody;
import com.code2roc.fastboot.framework.model.Result;
import com.code2roc.fastboot.framework.util.ConvertOp;
import com.code2roc.fastboot.framework.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system/setting/menu")
public class SystemMenuController extends BaseBootController {
    @Autowired
    private ISystemMenuService service;
    @Autowired
    private MenuLogic menuLogic;

    @ResponseBody
    @PostMapping("/tree")
    public Object tree(@RequestBody Map<String, Object> params) {
        Result result = Result.okResult();
        List<SystemMenuDO> entityList =  service.selectAllList();
        List<ZTreeNode> treeNodeList = new ArrayList<ZTreeNode>();
        for (SystemMenuDO entity:entityList) {
            ZTreeNode tree = new ZTreeNode();
            tree.setId(entity.getMenu_code());
            tree.setpId(entity.getMenu_code().substring(0, entity.getMenu_code().length() - 4));
            tree.setName(entity.getMenu_name());
            tree.setSotNum(entity.getSort_num());
            if(entity.getMenu_code().length()==4){
                tree.setTopNode(true);
            }
            tree.addAttribute("icon",entity.getIcon());
            tree.addAttribute("url",entity.getUrl());
            tree.addAttribute("openmodel",entity.getOpen_mode());
            treeNodeList.add(tree);
        }
        List<ZTreeNode> obj = ZTreeBuilder.BuildTree(treeNodeList);
        return result.add("obj",obj);
    }

    @ResponseBody
    @PostMapping("/getTopMenuList")
    public Object getTopMenuList(@RequestBody Map<String, Object> params) {
        Result result = Result.okResult();
        List<SystemMenuDO> entityList =  menuLogic.getUserMenuList();
        if(entityList.size()>0){
            entityList = entityList.stream().filter(a->a.getMenu_code().length()==4).collect(Collectors.toList());
        }
        return result.add("obj",entityList);
    }

    @ResponseBody
    @PostMapping("/getSubMenuTreeData")
    public Object getSubMenuTreeData(@RequestBody Map<String, Object> params) {
        Result result = Result.okResult();
        String menu_id = ConvertOp.convert2String(params.get("menu_id"));
        List<SystemMenuDO> entityList =  menuLogic.getUserMenuList();
        SystemMenuDO topMenu = service.selectOne(menu_id);
        if(entityList.size()>0){
            entityList = entityList.stream().filter(a->a.getRow_id()!=menu_id).collect(Collectors.toList());
        }
        List<ZTreeNode> treeNodeList = new ArrayList<ZTreeNode>();
        for (SystemMenuDO entity:entityList) {
            ZTreeNode tree = new ZTreeNode();
            tree.setId(entity.getMenu_code());
            tree.setpId(entity.getMenu_code().substring(0, entity.getMenu_code().length() - 4));
            tree.setName(entity.getMenu_name());
            tree.setSotNum(entity.getSort_num());
            if(entity.getParent_menu_code().equals(topMenu.getMenu_code())){
                tree.setTopNode(true);
            }
            tree.addAttribute("icon",entity.getIcon());
            tree.addAttribute("url",entity.getUrl());
            tree.addAttribute("openmodel",entity.getOpen_mode());
            treeNodeList.add(tree);
        }
        List<ZTreeNode> obj = ZTreeBuilder.BuildTree(treeNodeList);
        return result.add("obj",obj);
    }

    @ResponseBody
    @PostMapping("/getMenu")
    public Object getMenu(@RequestBody Map<String, Object> params) {
        Result result = Result.okResult();
        List<SystemMenuDO> entityList =  menuLogic.getUserMenuList();
        List<ZTreeNode> treeNodeList = new ArrayList<ZTreeNode>();
        for (SystemMenuDO entity:entityList) {
            ZTreeNode tree = new ZTreeNode();
            tree.setId(entity.getMenu_code());
            tree.setpId(entity.getMenu_code().substring(0, entity.getMenu_code().length() - 4));
            tree.setName(entity.getMenu_name());
            tree.setSotNum(entity.getSort_num());
            if(entity.getMenu_code().length()==4){
                tree.setTopNode(true);
            }
            tree.addAttribute("icon",entity.getIcon());
            tree.addAttribute("url",entity.getUrl());
            tree.addAttribute("openmodel",entity.getOpen_mode());
            treeNodeList.add(tree);
        }
        List<ZTreeNode> obj = ZTreeBuilder.BuildTree(treeNodeList);
        return result.add("obj",obj);
    }

    @ResponseBody
    @PostMapping("/list")
    public Object list(@RequestBody Map<String, Object> params) {
        Result result = Result.okResult();
        String sql = "1=1";
        HashMap<String, Object> paramMap = new HashMap<>();
        String menu_name = ConvertOp.convert2String(params.get("menu_name"));
        String menu_code = ConvertOp.convert2String(params.get("menu_code"));
        if (!StringUtil.isEmpty(menu_name)) {
            sql += " and menu_name like #{menu_name}";
            paramMap.put("menu_name", "%" + menu_name + "%");
        }
        if(!StringUtil.isEmpty(menu_code)){
            sql += " and menu_code like '" + menu_code + "%' and menu_code!='" + menu_code + "' and length(menu_code)=" + (menu_code.length() + 4) + "";
        }else{
            sql +=" and length(menu_code) =" + (menu_code.length() + 4);
        }
        List<SystemMenuDO> rows = service.selectPageList("*", sql, "sort_num desc", paramMap);
        int total = service.selectCount(sql, paramMap);
        result.add("rows", rows);
        result.add("total", total);
        return result;
    }

    @ResponseBody
    @PostMapping("/insert")
    @Transactional(rollbackFor = {Exception.class},isolation = Isolation.READ_UNCOMMITTED)
    public Object insert(@RequestBody SystemMenuDO entity) {
        Result result = Result.okResult();
        menuLogic.insert(entity);
        return result;
    }

    @ResponseBody
    @PostMapping("/detail")
    public Object detail(@RequestBody Map<String, Object> params) {
        Result result = Result.okResult();
        String row_id = ConvertOp.convert2String(params.get("row_id"));
        result.add("obj", menuLogic.detail(row_id));
        return result;
    }

    @ResponseBody
    @PostMapping("/update")
    @Transactional(rollbackFor = {Exception.class},isolation = Isolation.READ_UNCOMMITTED)
    public Object update(@UpdateRequestBody SystemMenuDO entity) {
        Result result = Result.okResult();
        menuLogic.update(entity);
        return result;
    }

    @ResponseBody
    @PostMapping("/batchUpdate")
    @Transactional(rollbackFor = {Exception.class},isolation = Isolation.READ_UNCOMMITTED)
    public Object batchUpdate(@UpdateRequestBody List<SystemMenuDO> entityList) {
        Result result = Result.okResult();
        service.batchUpdate(entityList);
        return result;
    }

    @ResponseBody
    @PostMapping("/delete")
    @Transactional(rollbackFor = {Exception.class},isolation = Isolation.READ_UNCOMMITTED)
    public Object delete(@RequestBody Map<String, Object> params) {
        Result result = Result.okResult();
        String row_id = ConvertOp.convert2String(params.get("row_id"));
        menuLogic.delete(row_id);
        return result;
    }

    @ResponseBody
    @PostMapping("/changeStatus")
    @Transactional(rollbackFor = {Exception.class},isolation = Isolation.READ_UNCOMMITTED)
    public Object changeStatus(@RequestBody Map<String, Object> params) throws Exception {
        Result result = Result.okResult();
        String row_id = ConvertOp.convert2String(params.get("row_id"));
        menuLogic.changeStatus(row_id);
        return result;
    }

    @ResponseBody
    @PostMapping("/exportData")
    public Object exportData(@RequestBody Map<String, Object> params) throws Exception {
        Result result = Result.okResult();
        String fileid = menuLogic.exportData();
        result.add("fileid", fileid);
        return result;
    }

    @ResponseBody
    @PostMapping("/importData")
    public Object importData(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        Result result = Result.okResult();
        String errormsg = menuLogic.importData(file.getInputStream());
        if (!StringUtil.isEmpty(errormsg)) {
            return Result.errorResult().setMsg(errormsg);
        }
        return result;
    }
}
